package com.gla.market.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gla.market.R;
import com.gla.market.constant.Constants;
import com.gla.market.utils.NetUtil;
import com.gla.market.utils.SharedPreferencesUtil;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddAddressActivity extends AppCompatActivity implements TencentLocationListener {

    Button back,save;
    EditText receive_getman2,receive_phone2,receive_area2,receive_name2;
    CheckBox is_default;
    ImageButton receive_location;

    int user_id;
    String addressArea,addressName;
    int flag;

    private Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);
        initView();
        //返回按钮
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //保存按钮
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addAddress();
            }
        });
        //获取定位按钮
        receive_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getLocation();
            }
        });
        //设为默认地址按钮
        is_default.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    flag = 1;
                }else{
                    flag =0;
                }
            }
        });
    }
    private void initView() {
        back = findViewById(R.id.back);
        receive_getman2 = findViewById(R.id.receive_getman2);
        receive_phone2 = findViewById(R.id.receive_phone2);
        receive_area2 = findViewById(R.id.receive_area2);
        receive_name2 = findViewById(R.id.receive_name2);
        is_default = findViewById(R.id.is_default);
        save = findViewById(R.id.save);
        receive_location = findViewById(R.id.receive_location);
        //从文件中获取user_id
        user_id = (int) SharedPreferencesUtil.get(this,"userInfo","user_id",7);
    }
    /**
     * 保存
     */
    public void addAddress() {
        if (!validate()) {
            addAddressFailed();
            return;
        }
        String receive_area = receive_area2.getText().toString();
        String receive_name = receive_name2.getText().toString();
        String receive_getman = receive_getman2.getText().toString();
        String receive_phone = receive_phone2.getText().toString();
        postAddAddressRequest(receive_area,receive_name,receive_getman,receive_phone);
    }
    private void postAddAddressRequest(String area, String name,String getman,String phone) {
        //将数据传给后端
        RequestBody body = new FormBody.Builder()
                .add("user_id",String.valueOf(user_id))
                .add("area", area)
                .add("name", name)
                .add("getman",getman)
                .add("is_default",String.valueOf(flag))
                .add("phone", phone).build();

        //发送修改请求
        NetUtil.doPost(Constants.BASE_URL + Constants.ADD_Address_URL, body, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = -1;
                mHandler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                Message message = Message.obtain();
                //获取返回结果
                String result = response.body().string().trim();
                Log.d("result",result);
                try {
                    JSONObject json = JSON.parseObject(result);
                    if (json.getInteger("status")==0) {
                        message.what = 1;
                    } else {
                        message.what = 0;
                    }
                } catch (Exception e) {
                    Log.e("network error!", e.getMessage());
                    message.what = 0;
                    message.obj = "请求响应失败！";
                }
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 注册消息handler
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    addAddressSuccess();
                    break;
                default:
                    addAddressFailed();
                    break;
            }
        }
    };

    public boolean validate() {
        boolean valid = true;

        String area1 = receive_area2.getText().toString();
        String name1 = receive_name2.getText().toString();
        String getman1 = receive_getman2.getText().toString();
        String phone1 = receive_phone2.getText().toString();

        //收货人错误
        if (TextUtils.isEmpty(getman1)) {
            receive_getman2.setError("收货人不能为空");
            valid = false;
        } else if (getman1.length()>5){
            receive_getman2.setError("昵称长度不得超过5，请修改！");
            valid = false;
        }
        //手机号码错误
        if (phone1.isEmpty()) {
            receive_phone2.setError("请输入电话号码！");
            valid = false;
        } else if(!(phone1.length()==11)){
            receive_phone2.setError("请输入11位正确的手机号码");
            valid = false;
        }
        //所在地区错误
        if (TextUtils.isEmpty(area1)) {
            receive_area2.setError("收货人不能为空");
            valid = false;
        }
        //详细地址错误
        if (TextUtils.isEmpty(name1)) {
            receive_name2.setError("收货人不能为空");
            valid = false;
        }
        return valid;
    }

    public void addAddressSuccess() {
        Toast.makeText(this, "保存成功!", Toast.LENGTH_SHORT).show();
        save.setEnabled(true);

        //更新sp数据
        SharedPreferences sharedPreferences = getSharedPreferences("addressInfo", Context.MODE_PRIVATE); //私有数据
        //保存用户信息
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("addressArea", addressArea);
        editor.putString("addressName", addressName);
        editor.commit();//提交修改

        Intent intent = new Intent(AddAddressActivity.this,ReceivingAddressActivity.class);
        startActivity(intent);
        finish();
    }

    public void addAddressFailed() {
        Toast.makeText(getBaseContext(), "保存失败", Toast.LENGTH_LONG).show();
        save.setEnabled(true);
    }
    public void getLocation(){
        //获取定位
        TencentLocationManager mLocationManager = TencentLocationManager.getInstance(mContext);
        mLocationManager.requestSingleFreshLocation(null, this, Looper.getMainLooper());
    }

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
        receive_area2.setText(tencentLocation.getAddress());
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }
}